package cn.hiapi.core.basic.query;


import cn.hiapi.core.basic.pageable.PageRequest;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author AdinZ
 * @date 2021/1/20 1:57 下午
 */
@Getter
@Setter
public abstract class BasicQuery {

    /**
     * 页码
     */
    protected int page = 1;
    /**
     * 页数
     */
    protected int size = 20;

    /**
     * 排序方向
     */
    protected Sort.Direction direction = Sort.Direction.DESC;
    /**
     * 排序字段
     */
    protected String[] properties;

    private String[] fields = new String[]{};


    /**
     * 自定义外部查询
     */
    private List<CustomQuery> customs = new ArrayList<>();


    /**
     * 实现查询条件
     *
     * @return
     */
    public abstract QueryWrapper getQueryWrapper();

    private QueryWrapper wrapper = new QueryWrapper();


    protected QueryWrapper getBasicQueryWrapper() {
        QueryWrapper wrapper = this.getQueryWrapper();
        this.wrapper.merge(wrapper);
        return this.wrapper;
    }

    public PageRequest getPageable() {
        if (this.properties == null || this.properties.length == 0) {
            return PageRequest.of(this.page, this.size);
        } else {
            if (this.direction == null) this.direction = Sort.Direction.DESC;
            return PageRequest.of(this.page, this.size, direction, properties);
        }
    }

    public void setPage(int page, int size) {
        this.page = page;
        this.size = size;
    }

    /***
     * 自定义搜索参数
     */
    public void setCustomQuery(CustomQuery.Result result) {
        if (StringUtils.isNotEmpty(result.getField())) {
            if (result.getType() != null) {
                wrapper.of(result.getType(), result.getField(), result.getValue());
            } else {
                if (result.getValue() instanceof Collection) {
                    wrapper.in(result.getField(), (Collection) result.getValue());
                } else wrapper.eq(result.getField(), result.getValue());
            }
        }
    }


    public void setProperties(String... properties) {
        this.properties = properties;
    }


}
